/*
 * Copyright 2016 Stuart Kent
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.example.mybugshaker.flow.email;

import ohos.app.Context;
import ohos.bundle.ApplicationInfo;
import ohos.bundle.BundleInfo;
import ohos.bundle.IBundleManager;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.rpc.RemoteException;
import org.jetbrains.annotations.NotNull;

public final class App {
    @NotNull
    private final String name;

    @NotNull
    private final String versionName;

    private final int versionCode;

    @NotNull
    private final InstallSource installSource;

    private final HiLogLabel lable = new HiLogLabel(HiLog.LOG_APP, 0x00201, "App");

    public App(@NotNull final Context context) {

        final IBundleManager iBundleManager = context.getBundleManager();
        final ApplicationInfo applicationInfo = context.getApplicationInfo();
        final BundleInfo bundleInfo = getPackageInfo(context);
        String installerPackageName = null;
        try {
            installerPackageName = iBundleManager.getApplicationInfo(context.getBundleName(),0,0).getName();
        } catch (RemoteException e) {
            HiLog.error(lable,"App", e);
        }
        name = applicationInfo.getLabel();
        versionName = bundleInfo.getName();
        versionCode = bundleInfo.getUid();
        installSource = InstallSource.fromInstallerPackageName(installerPackageName);
    }
    @NotNull
    public String getName() {
        return name;
    }

    @NotNull
    public String getVersionName() {
        return versionName;
    }

    public int getVersionCode() {
        return versionCode;
    }

    @NotNull
    public InstallSource getInstallSource() {
        return installSource;
    }

    private BundleInfo getPackageInfo(@NotNull final Context context) {
        final IBundleManager iBundleManager = context.getBundleManager();
        try {
            return iBundleManager.getBundleInfo(context.getBundleName(),0);
        } catch (RemoteException e) {
            HiLog.error(lable,"App", e);
            //noinspection ConstantConditions: packageInfo should always be available for the embedding app.
            return null;
        }
    }
}
